package practice;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class _BFS_ {
    public static void main(String[] args){
        _BFS_ c = new _BFS_();
        _BFS_.Solution s = c.getSolution();
        TreeNode n1 = new TreeNode(8);
        TreeNode n2 = new TreeNode(6);
        TreeNode n3 = new TreeNode(10);
        TreeNode n4 = new TreeNode(5);
        TreeNode n5 = new TreeNode(7);
        TreeNode n6 = new TreeNode(9);
        TreeNode n7 = new TreeNode(11);
        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n2.right = n5;
        n3.left = n6;
        n3.right = n7;
        List<List<TreeNode>> res = s.BFS(n1);
        System.out.println("finish...");
    }

    Solution getSolution() {
        return new Solution();
    }

    class  Solution{
       //非递归的解法
        /* public List<TreeNode> BFS(TreeNode root) {
            List<TreeNode> res = new ArrayList<>();
            Queue<TreeNode> ope = new LinkedList<>();
            if (root != null) ope.add(root);
            else return null;
            while (!ope.isEmpty()){
                for (int i = 0; i < ope.size(); i++) {
                    res.add(ope.peek());
                    if (ope.peek().left != null) ope.add(ope.peek().left);
                    if (ope.peek().right != null) ope.add(ope.peek().right);
                    ope.poll();
                }
            }
            return res;
        }*/


        //递归的方法
        public List<List<TreeNode>> BFS(TreeNode root) {
            if (root == null) return null;
            List<List<TreeNode>> list = new ArrayList<>();
            dfs(root,0,list);
            return list;
        }

        private void dfs(TreeNode root, int level, List<List<TreeNode>> list) {
            if (root == null) return;;
            if (level >= list.size()){
                List<TreeNode> subList = new ArrayList<>();
                subList.add(root);
                list.add(subList);
            }else {
                list.get(level).add(root);
            }
            dfs(root.left, level+1, list);
            dfs(root.right, level+1, list);
        }
    }

}
